package com.work.yshop.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationBarView;
import com.work.yshop.R;
import com.work.yshop.adapter.MainPagerAdapter;
import com.work.yshop.databinding.ActivityMainBinding;
import com.work.yshop.mvp.contract.LoginContract;
import com.work.yshop.mvp.contract.MainContract;
import com.work.yshop.mvp.presenter.MainPresenter;
import com.work.yshop.ui.fragment.AgriCircleFragment;
import com.work.yshop.ui.fragment.AgriTechFragment;
import com.work.yshop.ui.fragment.HomeFragment;
import com.work.yshop.ui.fragment.MessageFragment;
import com.work.yshop.ui.fragment.ProfileFragment;
import com.work.yshop.ui.fragment.SellerHomeFragment;
import com.work.yshop.utils.UserSession;

import java.util.ArrayList;
import java.util.List;

/**
 * 应用主页面 - MVP架构
 */
public class MainActivity extends AppCompatActivity implements MainContract.View {

    private ActivityMainBinding binding;
    private MainPagerAdapter pagerAdapter;
    private MainPresenter presenter;
    private final List<Fragment> fragments = new ArrayList<>();
    
    // 用户类型
    private int userType;
    
    // 买家页面索引
    private static final int BUYER_PAGE_HOME = 0;
    private static final int BUYER_PAGE_AGRI_TECH = 1;
    private static final int BUYER_PAGE_MESSAGE = 2;
    private static final int BUYER_PAGE_PROFILE = 3;
    
    // 卖家页面索引
    private static final int SELLER_PAGE_HOME = 0;
    private static final int SELLER_PAGE_AGRI_CIRCLE = 1;
    private static final int SELLER_PAGE_MESSAGE = 2;
    private static final int SELLER_PAGE_PROFILE = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        
        // 获取用户类型
        userType = getIntent().getIntExtra("user_type", LoginContract.USER_TYPE_BUYER);
        
        // 设置状态栏 - 移到setContentView之后
        setupStatusBar();
        
        // 初始化Presenter
        presenter = new MainPresenter();
        presenter.attachView(this);
        
        // 初始化视图和事件
        initViews();
        setupListeners();
    }
    
    /**
     * 设置状态栏
     */
    private void setupStatusBar() {
        // 让内容区域延伸到状态栏
        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
        
        // 设置状态栏图标为浅色
        WindowInsetsControllerCompat controller = new WindowInsetsControllerCompat(getWindow(), getWindow().getDecorView());
        controller.setAppearanceLightStatusBars(false); // 状态栏文字和图标为白色
        
        // 设置状态栏颜色为透明
        getWindow().setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
        
        // 设置状态栏背景View的高度
        int statusBarHeight = getStatusBarHeight();
        ViewGroup.LayoutParams layoutParams = binding.statusBarBg.getLayoutParams();
        layoutParams.height = statusBarHeight;
        binding.statusBarBg.setLayoutParams(layoutParams);
    }
    
    /**
     * 获取状态栏高度
     */
    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 初始化各个视图
     */
    private void initViews() {
        // 根据用户类型初始化不同的Fragment
        if (userType == LoginContract.USER_TYPE_BUYER) {
            // 买家页面
            fragments.add(HomeFragment.newInstance());
            fragments.add(AgriTechFragment.newInstance());
            fragments.add(MessageFragment.newInstance());
            fragments.add(ProfileFragment.newInstance());
            
            // 设置买家底部导航菜单
            binding.bottomNavigationView.inflateMenu(R.menu.bottom_nav_menu_buyer);
        } else {
            // 卖家页面
            fragments.add(SellerHomeFragment.newInstance());
            fragments.add(AgriCircleFragment.newInstance());
            fragments.add(MessageFragment.newInstance());
            fragments.add(ProfileFragment.newInstance());
            
            // 设置卖家底部导航菜单
            binding.bottomNavigationView.inflateMenu(R.menu.bottom_nav_menu_seller);
        }
        
        // 设置ViewPager2适配器
        pagerAdapter = new MainPagerAdapter(this, fragments);
        binding.viewPager.setAdapter(pagerAdapter);
        
        // 禁用ViewPager2的滑动
        binding.viewPager.setUserInputEnabled(false);
        
        // 设置底部导航栏选中项
        binding.bottomNavigationView.setSelectedItemId(
                userType == LoginContract.USER_TYPE_BUYER ? 
                R.id.navigation_home : R.id.navigation_seller_home);
                
        // 确保发布按钮可见
        binding.fabPublish.setVisibility(View.VISIBLE);
    }

    /**
     * 设置事件监听器
     */
    private void setupListeners() {
        // ViewPager2页面切换监听
        binding.viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                // 根据用户类型和页面位置，更新底部导航栏选中项
                int navId;
                if (userType == LoginContract.USER_TYPE_BUYER) {
                    switch (position) {
                        case BUYER_PAGE_HOME:
                            navId = R.id.navigation_home;
                            break;
                        case BUYER_PAGE_AGRI_TECH:
                            navId = R.id.navigation_agri_tech;
                            break;
                        case BUYER_PAGE_MESSAGE:
                            navId = R.id.navigation_message;
                            break;
                        case BUYER_PAGE_PROFILE:
                            navId = R.id.navigation_profile;
                            break;
                        default:
                            navId = R.id.navigation_home;
                            break;
                    }
                } else {
                    switch (position) {
                        case SELLER_PAGE_HOME:
                            navId = R.id.navigation_seller_home;
                            break;
                        case SELLER_PAGE_AGRI_CIRCLE:
                            navId = R.id.navigation_agri_circle;
                            break;
                        case SELLER_PAGE_MESSAGE:
                            navId = R.id.navigation_message;
                            break;
                        case SELLER_PAGE_PROFILE:
                            navId = R.id.navigation_profile;
                            break;
                        default:
                            navId = R.id.navigation_seller_home;
                            break;
                    }
                }
                updateSelectedNavItem(navId);
            }
        });

        // 底部导航栏选择监听 - 使用新的API
        binding.bottomNavigationView.setOnItemSelectedListener(item -> 
            presenter.onNavigationItemSelected(item.getItemId()));

        // 设置发布按钮点击事件 - 通过Presenter处理
        binding.fabPublish.setOnClickListener(v -> {
            // 无论是买家还是卖家，都可以点击进入发布页面
            presenter.onPublishButtonClicked();
        });
    }

    @Override
    public void switchToPage(int position) {
        binding.viewPager.setCurrentItem(position, false);
    }

    @Override
    public void updateSelectedNavItem(int itemId) {
        binding.bottomNavigationView.setSelectedItemId(itemId);
    }

    @Override
    public void showLoading() {
        // 显示加载中UI
    }

    @Override
    public void hideLoading() {
        // 隐藏加载中UI
    }

    @Override
    public void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void navigateToPublish() {
        // 跳转到发布页面
        Intent intent = new Intent(this, PublishActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.detachView();
        }
    }
} 